/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * @author 品讯科技
 */

package com.px.pa.modulars.circle.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.px.basic.alone.core.base.BaseApiController;
import com.pig4cloud.pig.common.core.support.cache.RedisHelper;
import com.pig4cloud.pig.common.core.support.http.HttpCode;
import com.pig4cloud.pig.common.core.support.security.BouncyCastleProvider;
import com.pig4cloud.pig.common.core.util.R;
import com.px.basic.alone.security.annotation.Inner;
import com.px.basic.alone.security.jwt.JwtTokenUtil;
import com.px.basic.alone.security.jwt.payload.JwtPayLoad;
import com.px.basic.alone.security.util.SecurityUtils;
import com.px.fastfile.config.FastfileSiteConfig;
import com.px.fastfile.service.FastfileService;
import com.px.fastfile.vo.FastfileParam;
import com.px.msg.MessageService;
import com.px.pa.constants.*;
import com.px.pa.modulars.circle.entity.*;
import com.px.pa.modulars.circle.service.*;
import com.px.pa.modulars.circle.service.impl.PicDownload;
import com.px.pa.modulars.circle.vo.CircleActivityFindVo;
import com.px.pa.modulars.circle.vo.DecryptionVo;
import com.px.pa.modulars.circle.vo.ScanUserVo;
import com.px.pa.modulars.sysConfigSms.service.SysConfigSmsService;
import com.px.pa.modulars.upms.entity.SysUser;
import com.px.pa.modulars.upms.service.SysUserService;
import com.px.pa.modulars.utils.*;
import com.px.plugins.conversion.excel.util.ExcelBaseUtil;
import com.px.wx.mini.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.parameters.P;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.Security;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 用户
 *
 * @author 品讯科技
 * @date 2024-08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/circleuser" )
@Api(value = "circleuser", tags = "用户管理")
public class CircleUserController {

    @Value("${baiduyun.clientId}")
    private String clientId;
    @Value("${baiduyun.clientSecret}")
    private String clientSecret;
    @Autowired
    protected HttpServletRequest request;

    private final CircleUserService circleUserService;
    private final CircleWxInfoService circleWxInfoService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private CircleRegService circleRegService;

    private final SysConfigSmsService sysConfigSmsService;

    private final CircleOrganizationalService circleOrganizationalService;

    private final AuditConfigurationService auditConfigurationService;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private FastfileService fastfileService;
    @Autowired

    private CircleDynamicService circleDynamicService;
    @Autowired
    private WxAnalysisService wxAnalysisService;
    @Autowired
    private CircleEnableService circleEnableService;
    @Autowired
    private PicDownload picDownload;
    @Autowired
    private CircleCompanyService circleCompanyService;

    private final  CircleActivitySignService circleActivitySignService;

    private final  CircleActivityService circleActivityService;

    private final CircleCodeService circleCodeService;
    private final ScopeBusinessService scopeBusinessService;
    @Autowired
    private CircleWxInfoService wxInfoService;

    @Value("${api.tenant-key}")
    private String  tenantCode;

    protected String getTenant(){
        String appid = request.getHeader(tenantCode);

        if (appid == null){
            return  null;
        }

        String tenant = wxInfoService.getOne(new QueryWrapper<CircleWxInfo>()
                .eq("appid",appid)).getTenantCode();

        return tenant == null ? null : tenant;
    }
    @Autowired
    private SysUserService sysUserService;
    private SysUser getUser(){
        SysUser user = sysUserService.getById(SecurityUtils.getUser().getId());
        return user;
    }
    /**
     * 分页查询
     *
     * @param page       分页对象
     * @param circleUser 用户
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
     @PreAuthorize("@pms.hasPermission('circleUser_circleuser_get')" )
    public R getCircleUserPage(Page page, CircleUser circleUser) {



//        .isNotNull("organizational_id")
        Page<CircleUser> circleUserPage = circleUserService.page(page, new QueryWrapper<CircleUser>()
                .like(circleUser.getName() != null, "name", circleUser.getName())
                .like(circleUser.getPhone() != null, "phone", circleUser.getPhone())
                .like(circleUser.getCompanyName() != null, "company_name", circleUser.getCompanyName())
                .eq(circleUser.getChucai() != null, "chucai", circleUser.getChucai())
                .eq("is_del", IsDelEnum.IS_DEL_ENUM_ONE.getValue())  //未注销
                .ne("is_tourists",IsTouristsEnum.IS_TOURISTS_ENUM_TWO.getValue())
                .eq("tenant_code",getUser().getOnlyLogo())
                .orderByAsc("create_time"));
        circleUserPage.getRecords().forEach(a -> {
            if (a.getOrganizationalId() != null) {
                CircleOrganizational circleOrganizational = circleOrganizationalService.getById(a.getOrganizationalId());
                if (circleOrganizational!=null){
                    a.setOrganizationalName(circleOrganizational.getName());
                    a.setOrganizationalIsDetail(circleOrganizational.getIsDetail());
                }

            }
           try{
               Calendar cal = Calendar.getInstance();
               int year = cal.get(Calendar.YEAR);
               a.setAge(year - a.getBirthYear());
           }catch (Exception e){

           }

           List<CircleCompany> circleCompanyList = circleCompanyService.list(new QueryWrapper<CircleCompany>().eq("uid",a.getId()).orderByDesc("create_time"));
           if(circleCompanyList.size()>0){
               a.setCircleCompany(circleCompanyList.get(0));
           }

        });
        return R.ok(circleUserPage);
    }



    /**
     * 离职列表
     *
     * @param page       分页对象
     * @param circleUser 用户
     * @return
     */
    @ApiOperation(value = "离职列表", notes = "离职列表")
    @GetMapping("/page1")
    // @PreAuthorize("@pms.hasPermission('circleUser_circleuser_get')" )
    public R getCircleUserPage1(Page page, CircleUser circleUser) {
//                .isNotNull("organizational_id")
        Page<CircleUser> circleUserPage = circleUserService.page(page, new QueryWrapper<CircleUser>()
                .eq("tenant_code",getUser().getOnlyLogo())
                .like(circleUser.getName() != null, "name", circleUser.getName())
                .like(circleUser.getPhone() != null, "phone", circleUser.getPhone())
                .like(circleUser.getCompanyName() != null, "company_name", circleUser.getCompanyName())
                .eq("is_del", IsDelEnum.IS_DEL_ENUM_TWO.getValue())  //未注销
                .ne("is_tourists",IsTouristsEnum.IS_TOURISTS_ENUM_TWO.getValue())
                .orderByAsc("create_time"));
        circleUserPage.getRecords().forEach(a -> {
            if (a.getOrganizationalId() != null) {
                CircleOrganizational circleOrganizational = circleOrganizationalService.getById(a.getOrganizationalId());
                a.setOrganizationalName(circleOrganizational.getName());
                a.setOrganizationalIsDetail(circleOrganizational.getIsDetail());
            }
            try{
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                a.setAge(year - a.getBirthYear());
            }catch (Exception e){

            }

            List<CircleCompany> circleCompanyList = circleCompanyService.list(new QueryWrapper<CircleCompany>().eq("uid",a.getId()).orderByDesc("create_time"));
            if(circleCompanyList.size()>0){
                a.setCircleCompany(circleCompanyList.get(0));
            }

        });
        return R.ok(circleUserPage);
    }


    /**
     * 通过id查询用户
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleUser_circleuser_get')")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(circleUserService.getById(id));
    }

    /**
     * 新增用户
     *
     * @param circleUser 用户
     * @return R
     */
    @ApiOperation(value = "新增用户", notes = "新增用户")
    // @SysLog("新增用户" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('circleUser_circleuser_add')")
    public R save(@RequestBody CircleUser circleUser) {

       CircleUser  circleUser1 = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(StringUtils.isNotEmpty(circleUser.getPhone()),"phone",circleUser.getPhone())
       .eq("tenant_code",getUser().getOnlyLogo()));
       if(circleUser1 != null){
           return R.failed("此手机号已被注册不能再次使用");
       }
       if(!StringUtils.isNotEmpty(circleUser.getHeadPic())){
           circleUser.setHeadPic("https://yctk-1256675456.cos.ap-nanjing.myqcloud.com/1000001771303685..png");
       }
       circleUser.setTenantCode(getUser().getOnlyLogo());
        return R.ok(circleUserService.save(circleUser));
    }

    /**
     * 修改用户
     *
     * @param circleUser 用户
     * @return R
     */
    @ApiOperation(value = "修改用户", notes = "修改用户")
    //@SysLog("修改用户" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('circleUser_circleuser_edit')")
    public R updateById(@RequestBody CircleUser circleUser) {
        //修改用户信息更新文章的用户名
        if(StringUtils.isNotBlank(circleUser.getName())){
         List<CircleDynamic> circleDynamicList =   circleDynamicService.list(new QueryWrapper<CircleDynamic>().eq("uid",circleUser.getId()));
            circleDynamicList.forEach(a->{
                a.setUname(circleUser.getName());
                circleDynamicService.updateById(a);
            });

        }
        return R.ok(circleUserService.updateById(circleUser));
    }

    /**
     * 通过id删除用户
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除用户", notes = "通过id删除用户")
    // @SysLog("通过id删除用户" )
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('circleUser_circleuser_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(circleUserService.removeById(id));
    }







    /**
     * 手机号直接登录
     */
    @GetMapping(value = "/phone/login")
    @ApiOperation("手机号直接登录")
    @Inner(value = false)
    public Object phoneLogin(@RequestParam(value = "phone") String phone, @RequestParam(value = "code") String code, @RequestParam(value = "phoneCode") String phoneCode


    ) {
        Map<String, Object> result = new HashMap<>();
        //查询万能码
     List<CircleCode>  circleCodeList = circleCodeService.list();
       if(circleCodeList.size() !=0){
           CircleCode circleCode = circleCodeList.get(0);
           if(StringUtils.isNotEmpty(circleCode.getCode())){

               if(!circleCode.getCode().equals(phoneCode)){
                   if (redisTemplate.opsForValue().get(phone) == null) {
                       return R.failed("验证码失效");
                   }
                   if (!redisTemplate.opsForValue().get(phone).equals(phoneCode) ) {
                       return R.failed("验证码不正确");
                   }
               }
           }else {
               if (redisTemplate.opsForValue().get(phone) == null) {
                   return R.failed("验证码失效");
               }
               if (!redisTemplate.opsForValue().get(phone).equals(phoneCode) ) {
                   return R.failed("验证码不正确");
               }
           }
       }else {
           if (redisTemplate.opsForValue().get(phone) == null) {
               return R.failed("验证码失效");
           }
           if (!redisTemplate.opsForValue().get(phone).equals(phoneCode) ) {
               return R.failed("验证码不正确");
           }

       }


            CircleWxInfo circleWxInfo = circleWxInfoService.list().get(0);
            CircleUser allUser = null;
            String wxOpenid = null;

            final WxMaService wxService = WxMaConfiguration.getMaService(circleWxInfo.getAppid(), circleWxInfo.getSecret());
            try {
                WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
                wxOpenid = session.getOpenid();
                //通过openid 查询用户信息把用户信息的openid设为空
                CircleUser circleUser2 =  circleUserService.getOne(new QueryWrapper<CircleUser>().eq(StringUtils.isNotEmpty(wxOpenid),"open_id",wxOpenid));
                if(circleUser2 != null){
                   if(StringUtils.isNotEmpty(circleUser2.getToken())){
                       redisTemplate.delete(circleUser2.getToken());
                   }


                    circleUser2.setOpenId("");
                    circleUserService.updateById(circleUser2);

                }
                CircleUser circleUser = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(phone != null, "phone", phone));
                if(circleUser == null){
                    return R.failed("您还未注册，请先去注册");
                }
                //如果用户不存在，则注册用户
                if (circleUser == null) {
                    CircleReg circleReg = circleRegService.getOne(new QueryWrapper<CircleReg>().eq("phone", phone));
                    CircleUser circleUser1 = new CircleUser();
                    circleUser1.setOpenId(wxOpenid);
                    circleUser1.setCreateTime(LocalDateTime.now());
                    circleUser1.setPhone(phone);
                    circleUser1.setRegId(circleReg.getId());
                    circleUser1.setIsTourists(2);
                    circleUserService.save(circleUser1);
                    //删除待注册信息
                    circleRegService.remove(new QueryWrapper<CircleReg>().eq("phone",phone));
                }else {

                    if(StringUtils.isNotEmpty(circleUser.getToken())){
                        redisTemplate.delete(circleUser.getToken());
                    }
                    circleUser.setOpenId(wxOpenid);
                    circleUserService.updateById(circleUser);

                }



                if (circleUser.getIsDel() == 2){
                    return R.failed("账号已停用");
                }

                JwtPayLoad payLoad = new JwtPayLoad(circleUser.getId().toString(), circleUser.getOpenId(), "xxxx");
                //创建token
                String token = JwtTokenUtil.generateToken(payLoad);




                redisHelper.getRedisTemplate().boundValueOps(token).set(circleUser.getId());
                CircleUser circleUser1 = circleUserService.getOne(new QueryWrapper<CircleUser>().eq(wxOpenid != null, "open_id", wxOpenid));
                circleUser1.setToken(token);
                circleUserService.updateById(circleUser1);
                result.put("token",token);
                //分享是否开启
                try{
                    CircleEnable circleEnable =  circleEnableService.list().get(0);
                    if(circleEnable != null){
                        circleUser1.setType(circleEnable.getType());
                    }
                }catch (Exception e){
                    System.out.println("开启分享失败");
                }
                result.put("circleUser", circleUser1);

            } catch (Exception e) {
                e.printStackTrace();
            }

        return R.ok(result);

    }


    /**
     * 解密手机号
     */
    @ApiOperation("解密手机号")
    @GetMapping(value = "/decrypt")
    @Inner(value = false)
    public Object decrypt(@RequestParam(value = "code", required = false) String code, @RequestParam(value = "encryptedData", required = false) String encryptedData,
                          @RequestParam(value = "iv", required = false) String iv) {
        WxMaService wxMaService =   getWxService();

        try {
            WxMaJscode2SessionResult  session = wxMaService.getUserService().getSessionInfo(code);
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(),encryptedData,iv);
            if(StringUtils.isNotEmpty(phoneNoInfo.getPhoneNumber()) || phoneNoInfo != null){
                return R.ok(phoneNoInfo.getPhoneNumber());
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return R.failed("请使用手机号登录");
        }
        return R.ok();
    }

    public WxMaService getWxService(){
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        String tenant = getTenant();
        CircleWxInfo circleWxInfo = circleWxInfoService.getOne(new QueryWrapper<CircleWxInfo>().eq("tenant_code", tenant));
        config.setAppid(circleWxInfo.getAppid());
        config.setSecret(circleWxInfo.getSecret());
        WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(config);
        return service;
    }


    /**
     * 发送短信接口
     */



    /**
     * 发送短信接口
     */





    @ApiOperation(value = "上传文件，根据key去找对应的配置文件")
    @PostMapping(value = "/fastfile/upload/{key}")
    @Inner(value = false)
    public Object imageUp(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response, @PathVariable("key") String key) {
        Map<String, Object> upResult = this.fastfileService.uploadFile(key, file);
        return R.ok(upResult);
    }

    @ApiOperation(value = "使用base64上传图片文件，根据key去找对应的配置文件")
    @PostMapping(value = "/base64/{key}")
    @Inner(value = false)
    public Object imageUp(@RequestBody FastfileParam param,
                          HttpServletRequest request,
                          HttpServletResponse response,
                          @PathVariable("key") String key) {
        FastfileSiteConfig siteConfig = this.fastfileService.getSiteConfig(key);
        File file = this.fastfileService.baseToFile(siteConfig, param.getData());
        ImgUtil.pressText(file, file, "测试文字", Color.RED, new Font("黑体", Font.BOLD, 100), 0, 0, 0.8f);
        Map<String, Object> upResult = this.fastfileService.uploadFile(key, file);
        return R.ok(upResult);
    }


    /**
     * 首页
     *
     * @return
     */
    @ApiOperation(value = "首页", notes = "首页")
    @GetMapping("/page/homelist")
    public R getHomeList(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize,
                         @RequestParam(required = false) String keyWord, @RequestParam(required = false) String manageRange) {
        Page<CircleUser> circleUserPage = circleUserService.getPageHomeList(page, pageSize, keyWord, manageRange,getUser().getOnlyLogo());
        return R.ok(circleUserPage);
    }


    /**
     * 测试
     *
     * @return
     */
    @ApiOperation(value = "测试", notes = "测试")
    @GetMapping("/page/test/{key}")
    @Inner(value = false)
    public R getHomeList1(@RequestParam("url") String url) {
        String picName = "225296";
        Map<String,Object> map = new HashMap<>();
        try {
            map =   picDownload.saveImageToDisk(picName,"f:/circle1/",url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String kpath =  map.get("kpath").toString();
        return R.ok(kpath);


    }

    @ApiOperation(value = "上传文件，根据key去找对应的配置文件")
    @PostMapping(value = "/fastfile/fileupload/{key}")
    @Inner(value = false)
    public Object fileUp(@RequestParam MultipartFile multipartFile, @PathVariable("key") String key) {
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            List<String> l = Arrays.asList(org.apache.commons.lang3.StringUtils.split(originalFilename, "."));
            file=File.createTempFile(l.get(0), "."+l.get(1));
            file = new File("C:\\Users\\Administrator\\Desktop\\新建文本文档.txt");
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> upResult = this.fastfileService.uploadFile(key, file);
        return R.ok(upResult);
    }














    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/touristsActivityPage")
    @Inner(value = false)
    public R touristsActivityPage(Page page, Integer id) {
        Page<CircleActivitySign> sign = circleActivitySignService.page(page,new QueryWrapper<CircleActivitySign>()
        .eq("user_id",id)
        .ne("is_cancel",1)
                .eq("tenant_code",getUser().getOnlyLogo())
        );

        sign.getRecords().forEach(a-> {
            a.setActivityTitle(circleActivityService.getById(a.getActivityId()).getTotle());
        });

        return R.ok(sign);
    }



    /*
        注销用户
     */
    @GetMapping("/theCancellation")
    @Inner(value = false)
    public R theCancellation(Integer uid){
        //获取用户信息并修改
        CircleUser user = circleUserService.getById(uid);
        user.setIsDel(2);
        user.setName(CancellationUser.userName);
        user.setHeadPic(CancellationUser.headImg);
        circleUserService.updateById(user);

        //修改当前用户发布的活动
        //未开始/进行中活动
        List<CircleActivity> activities = circleActivityService.getAcitivyByDelUser(uid);
        if (activities != null){
            activities.forEach(a->{
                Date dateAS = Date.from(a.getActivityStartTime().atZone(ZoneId.systemDefault()).toInstant());
                Date dateAE = Date.from(a.getActivityEndTime().atZone(ZoneId.systemDefault()).toInstant());
                if(dateAS.compareTo(new Date()) == -1 && dateAE.compareTo(new Date()) == 1 ){
                    a.setActivityEndTime(LocalDateTime.now());
                    circleActivityService.updateById(a);
                }
            });

        }
        return R.ok();
    }


    /*
        恢复用户
     */
    @GetMapping("/restoreUser")
    public R restoreUser(Integer uid){
        //获取用户信息并修改
        CircleUser user = circleUserService.getById(uid);
        user.setIsDel(1);
        return R.ok(circleUserService.updateById(user));
    }








    @PostMapping("/import")
    public R importFile(MultipartFile file){

        String tenant = getUser().getOnlyLogo();
        if(file.isEmpty()){
            return R.failed("文件不能为空");
        }
        List<Map<?,Object>> result  = circleUserService.solveExcel(file,tenant);
        if (result.size()>0){
            return R.failed(result,"导入失败");
        }
        return R.ok();
    }

    @PostMapping("/importFileByOrganizationalId")
    public R importFileByOrganizationalId(MultipartFile file,String oid){

       String tenant = getUser().getOnlyLogo();

        if (oid==null){
            return R.failed("请选择部门");
        }
        if(file.isEmpty()){
            return R.failed("文件不能为空");
        }
        List<Map<?,Object>> result  = circleUserService.importFileByOrganizationalId(file,oid,tenant);
        if (result.size()>0){
            return R.failed(result,"导入失败");
        }
        return R.ok();
    }


    @GetMapping("/transfer")
    @Inner(value = false)
    public R transfer(Integer[] ids,String oid){
        List<Integer> idList =Arrays.asList(ids);

        List<CircleUser> userList = circleUserService.listByIds(idList);
        userList.forEach(a->{
            a.setOrganizationalId(oid);
        });

        return R.ok(circleUserService.updateBatchById(userList));
    }







    /**
     * 解密手机号
     */
    @ApiOperation("解密手机号")
    @PostMapping(value = "/decrypt1")
    @Inner(value = false)
    public R getPhone(@RequestBody DecryptionVo decryptionVo){


        CircleWxInfo circleWxInfo = circleWxInfoService.list().get(0);
        final WxMaService wxService = WxMaConfiguration.getMaService(circleWxInfo.getAppid(), circleWxInfo.getSecret());
        WxMaJscode2SessionResult session = null;
        String phone = null;
        try {
            session = wxService.getUserService().getSessionInfo(decryptionVo.getCode());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        AESForWeixinGetPhoneNumber aes=new AESForWeixinGetPhoneNumber(decryptionVo.getEncryptedData(),session.getSessionKey(),decryptionVo.getIv());
        WeixinPhoneDecryptInfo info=aes.decrypt();
        if (null==info){
            System.out.println("error");
            return R.ok();
        }else {
            if (!info.getWeixinWaterMark().getAppid().equals(circleWxInfo.getAppid())){
                System.out.println("wrong appId");
            }
            System.out.println(info.getPhoneNumber());

            return R.ok(info.getPhoneNumber());
        }
    }


    @Inner(value = false)
    @RequestMapping("/getAdminPeople")
    public R getAdminPeople(Integer type){
        return R.ok(circleUserService.getAdminPeople(type));
    }

    @Inner(value = false)
    @RequestMapping("/getAdminMonthPeople")
    public R getAdminMonthPeople(){
        return R.ok(circleUserService.getAdminMonthPeople());
    }


    /**
     * ocr名片识别
     */
    @GetMapping(value = "/ocr/identify")
    @ApiOperation("ocr名片识别")
    @Inner(value = false)
    public R getOcridentify(@RequestParam("file") String file) {
        OcrToken ocrToken = new OcrToken();
        return R.ok(ocrToken.getToken(file, clientId, clientSecret));
    }
}
